package com.touka.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.touka.common.Result;
import com.touka.entity.ShoppingCart;
import com.touka.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/shoppingCart")
@Slf4j
public class ShoppingCartController {

  @Autowired
  private ShoppingCartService shoppingCartService;

  /**
   * 获取当前登录用户的购物车数据
   *
   * @param session
   * @return
   */
  @GetMapping("/list")
  public Result<List<ShoppingCart>> list(HttpSession session) {
    log.info("获取购物车信息：{}", session.getAttribute("user"));

    List<ShoppingCart> shoppingCarts = shoppingCartService.list(
            Wrappers.lambdaQuery(ShoppingCart.class)
                    .eq(ShoppingCart::getUserId, session.getAttribute("user"))
                    .orderByDesc(ShoppingCart::getCreateTime)
    );

    return Result.success(shoppingCarts);
  }

  /**
   * 添加到购物车
   *
   * @param shoppingCart
   * @return
   */
  @PostMapping("/add")
  public Result<String> add(@RequestBody ShoppingCart shoppingCart, HttpSession session) {
    log.info("加入购物车：{}", shoppingCart);

    shoppingCart.setUserId((Long) session.getAttribute("user"));

    ShoppingCart cart = null;
    if (shoppingCart.getDishId() != null) {
      cart = shoppingCartService.getOne(
              Wrappers.lambdaQuery(ShoppingCart.class)
                      .eq(ShoppingCart::getDishId, shoppingCart.getDishId())
                      .eq(ShoppingCart::getUserId, shoppingCart.getUserId())
      );
    } else if (shoppingCart.getSetmealId() != null) {
      cart = shoppingCartService.getOne(
              Wrappers.lambdaQuery(ShoppingCart.class)
                      .eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId())
                      .eq(ShoppingCart::getUserId, shoppingCart.getUserId())
      );
    }

    if (cart != null) {
      // 已存在，数量+1
      cart.setNumber(cart.getNumber() + 1);
      shoppingCartService.updateById(cart);
    } else {
      shoppingCart.setCreateTime(LocalDateTime.now());
      shoppingCartService.save(shoppingCart);
    }

    return Result.success("加入成功");
  }

  /**
   * 移除购物车
   *
   * @param shoppingCart
   * @return
   */
  @PostMapping("/sub")
  public Result<String> sub(@RequestBody ShoppingCart shoppingCart, HttpSession session) {
    log.info("移除购物车：{}", shoppingCart);

    Long userId = (Long) session.getAttribute("user");

    ShoppingCart cart = null;
    if (shoppingCart.getDishId() != null) {
      cart = shoppingCartService.getOne(
              Wrappers.lambdaQuery(ShoppingCart.class)
                      .eq(ShoppingCart::getDishId, shoppingCart.getDishId())
                      .eq(ShoppingCart::getUserId, userId)
      );
    } else if (shoppingCart.getSetmealId() != null) {
      cart = shoppingCartService.getOne(
              Wrappers.lambdaQuery(ShoppingCart.class)
                      .eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId())
                      .eq(ShoppingCart::getUserId, userId)
      );
    }

    if (cart != null) {
      // 存在
      if (cart.getNumber() > 1) {
        // 减少数量
        cart.setNumber(cart.getNumber() - 1);
        shoppingCartService.updateById(cart);
      } else {
        // 直接删除
        shoppingCartService.removeById(cart.getId());
      }
    } else {
      // 不存在
      return Result.error("购物车中不存在该商品");
    }

    return Result.success("移除成功");
  }

  /**
   * 清空购物车
   *
   * @param session
   * @return
   */
  @DeleteMapping("/clean")
  public Result<String> clear(HttpSession session) {
    log.info("清空购物车：{}", session.getAttribute("user"));

    shoppingCartService.remove(
            Wrappers.lambdaQuery(ShoppingCart.class).eq(ShoppingCart::getUserId, session.getAttribute("user"))
    );

    return Result.success("清空成功");
  }
}
